import React, { useEffect, useMemo } from 'react';
import styled from 'styled-components';
import { useWallet } from 'use-wallet';

import Button from '../../components/Button';
import PageHeader from '../../components/PageHeader';
import Spacer from '../../components/Spacer';
import Harvest from './components/Harvest';
import Stake from './components/Stake';
import Harvest3 from './components/Harvest3';
import Stake3 from './components/Stake3';
import Harvest4 from './components/Harvest4';
import Stake4 from './components/Stake4';
import Harvest2 from './components/Harvest2';
import Stake2 from './components/Stake2';
import Harvest1 from './components/Harvest1';
import Stake1 from './components/Stake1';
import { Switch } from 'react-router-dom';
import Page from '../../components/Page';
import useRedeemOnBoardroom from '../../hooks/useRedeemOnBoardroom';
import useStakedBalanceOnBoardroom from '../../hooks/useStakedBalanceOnBoardroom';
import useRedeemOnBoardroom1 from '../../hooks/useRedeemOnBoardroom1';
import useStakedBalanceOnBoardroom1 from '../../hooks/useStakedBalanceOnBoardroom1';
import useRedeemOnBoardroom2 from '../../hooks/useRedeemOnBoardroom2';
import useStakedBalanceOnBoardroom2 from '../../hooks/useStakedBalanceOnBoardroom2';

import useRedeemOnBoardroom3 from '../../hooks/useRedeemOnBoardroom3';
import useStakedBalanceOnBoardroom3 from '../../hooks/useStakedBalanceOnBoardroom3';
import useRedeemOnBoardroom4 from '../../hooks/useRedeemOnBoardroom4';
import useStakedBalanceOnBoardroom4 from '../../hooks/useStakedBalanceOnBoardroom4';

import config from '../../config';
import LaunchCountdown from '../../components/LaunchCountdown';
import Stat from './components/Stat';
import ProgressCountdown from './components/ProgressCountdown';
import useCashPriceInEstimatedTWAP from '../../hooks/useCashPriceInEstimatedTWAP';
import useTreasuryAmount from '../../hooks/useTreasuryAmount';
import Humanize from 'humanize-plus';
import { getBalance } from '../../utils/formatBalance';
import useTreasuryAllocationTimes from '../../hooks/useTreasuryAllocationTimes';
import Notice from '../../components/Notice';
import useBoardroomVersion from '../../hooks/useBoardroomVersion';
import moment from 'moment';
import bg_board from '../../assets/image/bg_boardroom.png';

const Boardroom: React.FC = () => {
  useEffect(() => window.scrollTo(0, 0));
  const { account } = useWallet();
  const { onRedeem } = useRedeemOnBoardroom();
  const { onRedeem1 } = useRedeemOnBoardroom1();
  const { onRedeem2 } = useRedeemOnBoardroom2();
  const { onRedeem3 } = useRedeemOnBoardroom3();
  const { onRedeem4 } = useRedeemOnBoardroom4();
  const stakedBalance = useStakedBalanceOnBoardroom();
  const stakedBalance1 = useStakedBalanceOnBoardroom1();
  const stakedBalance2 = useStakedBalanceOnBoardroom2();
  const stakedBalance3 = useStakedBalanceOnBoardroom3();
  const stakedBalance4 = useStakedBalanceOnBoardroom4();

  const cashStat = useCashPriceInEstimatedTWAP();
  const treasuryAmount = useTreasuryAmount();
  const scalingFactor = useMemo(
    () => (cashStat ? Number(cashStat.priceInDAI).toFixed(2) : null),
    [cashStat],
  );
  const { prevAllocation, nextAllocation } = useTreasuryAllocationTimes();

  const prevEpoch = useMemo(
    () =>
      nextAllocation.getTime() <= Date.now()
        ? moment().utc().startOf('day').toDate()
        : prevAllocation,
    [prevAllocation, nextAllocation],
  );
  const nextEpoch = useMemo(() => moment(prevEpoch).add(8, 'hours').toDate(), [prevEpoch]);

  const boardroomVersion = useBoardroomVersion();
  const usingOldBoardroom = boardroomVersion !== 'latest';
  const migrateNotice = useMemo(() => {
    if (boardroomVersion === 'v2') {
      return (
        <StyledNoticeWrapper>
          <Notice color="green">
            <b>Please Migrate into New Boardroom</b>
            <br />
            The boardroom upgrade was successful. Please settle and withdraw your stake from the
            legacy boardroom, then stake again on the new boardroom contract{' '}
            <b>to continue earning ESC seigniorage.</b>
          </Notice>
        </StyledNoticeWrapper>
      );
    }
    return <></>;
  }, [boardroomVersion]);

  const isLaunched = Date.now() >= config.boardroomLaunchesAt.getTime();
  if (!isLaunched) {
    return (
      <Switch>
        <Page>
          <PageHeader
            icon={<img
              src={bg_board}
              alt='logo'
              width={310}
              height={250}
            />}
            title="加入EASY BANK董事會"
            subtitle="存入ESS賺取調整獎勵"
          />
          <LaunchCountdown
            deadline={config.boardroomLaunchesAt}
            description="董事會是如何運作的?"
            descriptionLink=""
          />
        </Page>
      </Switch>
    );
  }

  return (
    <Switch>
      <Page>
        {!!account ? (
          <>
            <PageHeader
              icon={<img
                src={bg_board}
                alt='logo'
                width={310}
                height={250}
              />}
              title="加入EASY BANK董事會"
              subtitle="存入ESS賺取通脹獎勵"
            />
            {migrateNotice}
            <StyledHeader>
              <ProgressCountdown
                base={prevEpoch}
                deadline={nextEpoch}
                description="下個週期"
              />
              <Stat
                icon="💵"
                title={cashStat ? `$${cashStat.priceInDAI}` : '-'}
                description="ESC平均價格"
              />
              <Stat
                icon="🚀"
                title={scalingFactor ? `x${scalingFactor}` : '-'}
                description="調整係數"
              />
              <Stat
                icon="💰"
                title={
                  treasuryAmount
                    ? `~$${Humanize.compactInteger(getBalance(treasuryAmount), 2)}`
                    : '-'
                }
                description="國庫金額"
              />
            </StyledHeader>
            <StyledBoardroom>
              <StyledCardsWrapper>
                <StyledCardWrapper>
                  <Harvest />
                </StyledCardWrapper>
                <Spacer />
                <StyledCardWrapper>
                  <Stake />
                </StyledCardWrapper>
              </StyledCardsWrapper>
              <Spacer size="lg" />
              {!usingOldBoardroom && (
                <>
                  <div>
                    <Button
                      disabled={stakedBalance.eq(0)}
                      onClick={onRedeem}
                      text="結算 & 提款"
                    />
                  </div>
                  <Spacer size="lg" />
                </>
              )}
            </StyledBoardroom>
            {/* 第二块 */}
            <StyledBoardroom>
              <StyledCardsWrapper>
                <StyledCardWrapper>
                <div style={{position:'absolute', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                  x90%</div>
                  <Harvest1 />
                </StyledCardWrapper>
                <Spacer />
                <StyledCardWrapper>
                <div style={{position:'absolute', display: 'flex', justifyContent: 'center', alignItems: 'center', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                72H</div>
                  <Stake1 />
                </StyledCardWrapper>
              </StyledCardsWrapper>
              <Spacer size="lg" />
              {!usingOldBoardroom && (
                // for old boardroom users, the button is displayed in Stake component
                <>
                  <div>
                    <Button
                      disabled={stakedBalance1.eq(0)}
                      onClick={onRedeem1}
                      text="結算 & 提款"
                    />
                  </div>
                  <Spacer size="lg" />
                </>
              )}
            </StyledBoardroom>
            {/* 第三块 */}
            <StyledBoardroom>
              <StyledCardsWrapper>
                <StyledCardWrapper>
                <div style={{position:'absolute', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                  x10%</div>
                  <Harvest2 />
                </StyledCardWrapper>
                <Spacer />
                <StyledCardWrapper>
                <div style={{position:'absolute', display: 'flex', justifyContent: 'center', alignItems: 'center', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                48H</div>
                  <Stake2 />
                </StyledCardWrapper>
              </StyledCardsWrapper>
              <Spacer size="lg" />
              {!usingOldBoardroom && (
                // for old boardroom users, the button is displayed in Stake component
                <>
                  <div>
                    <Button
                      disabled={stakedBalance2.eq(0)}
                      onClick={onRedeem2}
                      text="結算 & 提款"
                    />
                  </div>
                  <Spacer size="lg" />
                </>
              )}
            </StyledBoardroom>

            {/* 第伍块 */}
            <StyledBoardroom>
              <StyledCardsWrapper>
                <StyledCardWrapper>
                <div style={{position:'absolute', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                  x90%</div>
                  <Harvest4 />
                </StyledCardWrapper>
                <Spacer />
                <StyledCardWrapper>
                <div style={{position:'absolute', display: 'flex', justifyContent: 'center', alignItems: 'center', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                48H</div>
                  <Stake4 />
                </StyledCardWrapper>
              </StyledCardsWrapper>
              <Spacer size="lg" />
              {!usingOldBoardroom && (
                // for old boardroom users, the button is displayed in Stake component
                <>
                  <div>
                    <Button
                      disabled={stakedBalance4.eq(0)}
                      onClick={onRedeem4}
                      text="結算 & 提款"
                    />
                  </div>
                  <Spacer size="lg" />
                </>
              )}
            </StyledBoardroom>

            {/* 第四块 */}
            <StyledBoardroom>
              <StyledCardsWrapper>
                <StyledCardWrapper>
                <div style={{position:'absolute', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                  x10%</div>
                  <Harvest3 />
                </StyledCardWrapper>
                <Spacer />
                <StyledCardWrapper>
                <div style={{position:'absolute', display: 'flex', justifyContent: 'center', alignItems: 'center', top:'15px', left:'0px', background: '#fff', zIndex: 0, padding: '10px 25px', borderTopRightRadius: 20, borderBottomRightRadius: 20, color: '#2A169B', fontSize: '14px'}}>
                72H</div>
                  <Stake3 />
                </StyledCardWrapper>
              </StyledCardsWrapper>
              <Spacer size="lg" />
              {!usingOldBoardroom && (
                // for old boardroom users, the button is displayed in Stake component
                <>
                  <div>
                    <Button
                      disabled={stakedBalance3.eq(0)}
                      onClick={onRedeem3}
                      text="結算 & 提款"
                    />
                  </div>
                  <Spacer size="lg" />
                </>
              )}
            </StyledBoardroom>

            
          </>
        ) : (
          <UnlockWallet />
        )}
      </Page>
    </Switch>
  );
};

const UnlockWallet = () => {
  const { connect } = useWallet();
  return (
    <Center>
      <Button onClick={() => connect('injected')} text="連接錢包" />
    </Center>
  );
};

const StyledBoardroom = styled.div`
  align-items: center;
  display: flex;
  flex-direction: column;
  @media (max-width: 768px) {
    width: 100%;
  }
`;

const StyledHeader = styled.div`
  justify-content: center;
  display: flex;
  flex-direction: row;
  margin-bottom: ${(props) => props.theme.spacing[5]}px;
  width: 960px;

  > * {
    flex: 1;
    height: 84px;
    margin: 0 ${(props) => props.theme.spacing[2]}px;
  }

  @media (max-width: 768px) {
    flex-direction: column;
    width: 100%;
  }
`;

const StyledNoticeWrapper = styled.div`
  width: 768px;
  margin-top: -20px;
  margin-bottom: 40px;
`;

const StyledCardsWrapper = styled.div`
  display: flex;
  width: 600px;
  @media (max-width: 768px) {
    width: 100%;
    flex-flow: column nowrap;
    align-items: center;
  }
`;

const StyledCardWrapper = styled.div`
  display: flex;
  flex: 1;
  flex-direction: column;
  position: relative;
  @media (max-width: 768px) {
    width: 80%;
  }
`;

const Center = styled.div`
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
`;

export default Boardroom;
